package com.hydl.power.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hydl.power.mapper.InspectionOrderMapper;
import com.hydl.power.mapper.InspectionplanMapper;
import com.hydl.power.mapper.MaintainerMapper;
import com.hydl.power.mapper.SysUserMapper;
import com.hydl.power.pojo.InspectionOrder;
import com.hydl.power.pojo.Inspectionplan;
import com.hydl.power.pojo.Maintainer;
import com.hydl.power.pojo.SysUser;
import com.hydl.power.service.InspectionplanService;
import com.hydl.power.utils.Resp;
import com.hydl.power.utils.SmsUtils;
import com.hydl.power.utils.TableUtils;
import org.apache.poi.ss.formula.functions.T;
import org.hibernate.validator.constraints.br.TituloEleitoral;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class InspectionplanServiceImpl implements InspectionplanService {

    @Autowired
    private InspectionplanMapper inspectionplanMapper;
    @Autowired
    private InspectionOrderMapper inspectionOrderMapper;
    @Autowired
    private MaintainerMapper MaintainerMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 按条件查询计划
     * @param pageNum
     * @param pageSize
     * @param taskType
     * @param taskStatus
     * @param maintainerId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public PageInfo<Inspectionplan> selectByCondition(Integer pageNum, Integer pageSize, String taskType,
                                                  String taskStatus, String maintainerId, String startTime, String endTime,String token) {
        SysUser sysUser =sysUserMapper.getUserByToken(token);
        if(sysUser!=null){
            if(sysUser.getStatus()==2) {
                List<Inspectionplan> list = inspectionplanMapper.selectByCondition(pageNum,pageSize,taskType,taskStatus, maintainerId,  startTime,  endTime,sysUser.getProjectId().toString());
                return new PageInfo<>(list);
            }
        }




        return new PageInfo<>(inspectionplanMapper.selectByCondition(pageNum,pageSize,taskType,taskStatus, maintainerId,  startTime,  endTime,null));
    }

    /**
     * 添加计划
     * @param
     * @return
     */
    @Override
    @Transactional
    public int addPlan(String taskname,String tasktype,String taskcontent,String tasktime,
                        String taskstatus,String roomname,String roomid,String maintainer,String maintainerid,String projectId,String projectName,String runmode,String cityId,String cityName) {
              String[] str = tasktime.split(",");
              int flag = 0;
                for (String s : str) {
                   flag=  inspectionplanMapper.insert(taskname,tasktype,taskcontent,s,taskstatus,roomname,roomid,maintainer,maintainerid,projectId,projectName,runmode,cityId,cityName);
                }
          return flag;
    }

    /**
     * 删除计划
     * @param tid
     * @return
     */
    @Override
    public Resp delectPlan(Integer tid) {

        int res = inspectionplanMapper.deleteByPrimaryKey(tid);

        if (res > 0 ){

            return Resp.success("成功");

        }else {

            return Resp.fail("失败,不成功便成仁");
        }
    }


    @Override
    public int updateByPrimaryKeySelective(String taskname, String tasktype, String taskcontent, String tasktime,
                                           String taskstatus, String maintainer, String maintainerid, String roomname, String roomid, String runmode,
                                           String projectId,String projectName,String cityId,String cityName,Integer tid) {
        return inspectionplanMapper.updateByPrimaryKeySelective(taskname,tasktype,taskcontent,tasktime,taskstatus,maintainer,maintainerid,roomname,roomid,runmode,projectId,projectName,cityId,cityName,tid);
    }

    /**
     * 根据id查询计划
     * @param
     * @return
     **/
    @Override
    public Inspectionplan queryplanById(Integer tid) {
        return inspectionplanMapper.queryplanById(tid);
    }

    /**
     * 定时任务，每天早上八点执行
     * @param
     * @return
     **/
    @Override
    @Scheduled(cron = "0 0 8 * * ?")
    //@Scheduled(cron = "0 */1 * * * ?")
    public void queryplanByRunMode() {
      List<Inspectionplan> lsitOnce = inspectionplanMapper.queryplanByRunModeOnce(); // 查单次
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Map<String, String> map = new HashMap<String, String>();
        String data = "";
        long millisecond = 0;
        long taskTime = 0;
        String today = sdf.format(date);               //获取当前日期年月日
        //将当前日期转换为时间戳
        try {
          millisecond = sdf.parse(today).getTime();
        } catch (ParseException e) {
        e.printStackTrace();
      }
      if (lsitOnce.size() != 0) {
        for (Inspectionplan inspectionplan : lsitOnce) {
          if (inspectionplan.getTasktime().equals(today)) {
            System.out.println(inspectionplan.getTasktime());
            System.out.println(today);
            Maintainer Maintainer = MaintainerMapper.selectById1(inspectionplan.getMaintainerid());
            map.put("roomname", inspectionplan.getRoomname());
            map.put("task", today);
            data = JSONObject.toJSONString(map);
            SmsUtils.sendSms(Maintainer.getPhone(), "合一电力", "SMS_197891554", data);    // 发送短信的手机号、短信内容、短信定时时间（可为空）
          }
          //查询巡查计划表，如果当前时间大于执行时间，则状态改为已失效
          try {
            taskTime = sdf.parse(inspectionplan.getTasktime()).getTime();
          } catch (ParseException e) {
            e.printStackTrace();
          }
          if (millisecond > taskTime) {
            inspectionplanMapper.updateByPrimaryKeySelective(null, null, null, null, "1"
              , null, null, null, null, null, null, null, null, null, inspectionplan.getTid());
          }
        }

/*        //查询巡查工单,如果今天日期大于执行日期，并且状态为 未执行，则修改状态为 已失效
        List<InspectionOrder> inspectionOrder = inspectionOrderMapper.queryPatrolWorkOrder();
        if (inspectionOrder != null) {
          for (InspectionOrder order : inspectionOrder) {
            try {
              taskTime = sdf.parse(order.getStartTime()).getTime();   //获取被执行时间得时间戳
            } catch (ParseException e) {
              e.printStackTrace();
            }
            if (millisecond > taskTime && order.getStatus() == 0) {
              inspectionOrderMapper.updatePatrolWorkOrder(null, null, null, null, null, null,
                null, null, null, null, null, null, 4, order.getId());
            }
          }
        }*/
      }
    }

  @Override
  public List<InspectionOrder> queryStatus(String token) {
      SysUser sysUser = sysUserMapper.getUserByToken(token);
      List<InspectionOrder> list = new ArrayList<>();
      if(sysUser != null){
        if(sysUser.getStatus() !=2){
           list = inspectionOrderMapper.queryStatus(null);
        }else {
          list = inspectionOrderMapper.queryStatus(sysUser.getProjectId().toString());
        }
      }
    return list;
  }

    @Override
    public PageInfo<InspectionOrder> queryoOffTheStocks(Integer pageNum, Integer pageSize,String token, String createTime,String dataType) {
      SysUser sysUser=sysUserMapper.getUserByToken(token);
      List<InspectionOrder> list = new ArrayList<>();
      if(sysUser != null){
        if(sysUser.getStatus() ==2){
          list = inspectionOrderMapper.queryoOffTheStocks(pageNum,pageSize,createTime,dataType,sysUser.getProjectId().toString());
        }else {
          list = inspectionOrderMapper.queryoOffTheStocks(pageNum,pageSize,createTime,dataType,null);
        }
      }
      return new PageInfo<>(list);
    }
}
